# Java 版本切换脚本 - 切换到 Java 21
Write-Host "🔄 切换到 Java 21 LTS..." -ForegroundColor Green

# 查找已安装的Java版本
$javaInstallations = Get-ChildItem "C:\Program Files\Eclipse Adoptium\" -ErrorAction SilentlyContinue

Write-Host "📋 已安装的 Java 版本:" -ForegroundColor Yellow
$javaInstallations | ForEach-Object {
    Write-Host "  - $($_.Name)" -ForegroundColor Cyan
}

# 查找Java 21
$java21 = $javaInstallations | Where-Object { $_.Name -like "*jdk-21*" } | Select-Object -First 1

if ($java21) {
    $java21Path = $java21.FullName
    Write-Host "✅ 找到 Java 21: $java21Path" -ForegroundColor Green
    
    # 设置环境变量
    Write-Host "🔧 设置环境变量..." -ForegroundColor Yellow
    
    # 设置JAVA_HOME
    [Environment]::SetEnvironmentVariable("JAVA_HOME", $java21Path, "User")
    $env:JAVA_HOME = $java21Path
    
    # 更新PATH
    $currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
    $javaBin = "$java21Path\bin"
    
    # 移除所有Java相关路径
    $pathArray = $currentPath -split ";" | Where-Object { 
        $_ -notlike "*jdk*\bin" -and 
        $_ -notlike "*java*\bin" -and 
        $_ -notlike "*Eclipse Adoptium*" 
    }
    
    # 添加Java 21路径到开头（优先级最高）
    $newPath = ($javaBin, $pathArray) -join ";"
    [Environment]::SetEnvironmentVariable("Path", $newPath, "User")
    $env:Path = "$javaBin;$env:Path"
    
    Write-Host "✅ 环境变量更新完成！" -ForegroundColor Green
    Write-Host "JAVA_HOME: $java21Path" -ForegroundColor Cyan
    Write-Host "PATH 已更新" -ForegroundColor Cyan
    
    # 验证切换结果
    Write-Host "🧪 验证 Java 版本..." -ForegroundColor Yellow
    try {
        $javaVersion = & "$javaBin\java.exe" -version 2>&1
        Write-Host "当前 Java 版本:" -ForegroundColor Green
        Write-Host $javaVersion -ForegroundColor White
        
        # 检查Maven使用的Java版本
        Write-Host "🔍 检查 Maven 使用的 Java 版本..." -ForegroundColor Yellow
        $mavenJavaVersion = & mvn -version 2>&1
        Write-Host $mavenJavaVersion -ForegroundColor White
        
    } catch {
        Write-Host "⚠️ 无法验证版本，请重新启动终端" -ForegroundColor Yellow
    }
    
} else {
    Write-Host "❌ 未找到 Java 21 安装" -ForegroundColor Red
    Write-Host "请先运行 install-java21.ps1 安装 Java 21" -ForegroundColor Yellow
}

Write-Host "🎉 Java 版本切换完成！" -ForegroundColor Green
Write-Host "建议重新启动 PowerShell 或 IDE 以确保环境变量生效" -ForegroundColor Yellow